//
//  ApiLogin.swift
//  YOKO
//
//  Created by 鲁浩 on 16/5/19.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import Foundation
import Alamofire

class ApiLogin {
	let CODE = "code";// 短信验证码

	let USER_TYPE_WEIXIN = "user_type_wx";
	let USER_TYPE_QQ = "user_type_qq";
	let USER_TYPE_WEIBO = "user_type_wb";
	let USER_TYPE_PHONE = "user_type_phone";

	let NICKNAME = "nickname";
	let PORTRAIT = "portrait";
	let USER_TYPE = "user_type";

	let YOKO = "yoko";
	let ACCESS_TOKEN = "access_token";
	let REFRESH_TOKEN = "refresh_token";
	let USER_ID = "user_id";

	let GENDER = "gender";
	let PORTRAIT_SAVE_PATH = "portrait_save_path";
	let PHONE = "phone";

	let TIMESTAMP = "timestamp";
	let SESSION_KEY = "session_key";
	let REG_ID = "regId";

	// 根据手机号请求短信验证码
	func requestConfirmCode(phoneNumber: String, callback: (Bool?, String?) -> ()) {
		if (phoneNumber.isEmpty) {
			callback(false, "手机号为空。")
		}
		Alamofire.request(.POST, URL_REQUEST_SMS_CODE, parameters: [self.PHONE: phoneNumber], encoding: .JSON)
			.responseJSON { response in
				switch response.result {
				case .Success(let value as NSDictionary):
					if (value["status"] as! Int == 0) {
						callback(true, "成功！")
					} else {
						callback(false, value["message"] as? String)
					}
				case .Failure(_):
					callback(false, "连接服务器失败...")
				default:
					callback(false, "未知错误！")
				}
		}
	}

	// 根据手机号以及短信验证码请求token
	func verifyPhoneAndConfirmCode(phoneNumber: String, confirmCode: String, callback: (Bool?, String?) -> ()) {
		if (phoneNumber.isEmpty || confirmCode.isEmpty) {
			callback(false, "手机号或验证码为空。")
		}
		let apiParams = UrlBuilder()
		apiParams.appendParam(PHONE, value: phoneNumber)
		apiParams.appendParam(CODE, value: confirmCode)
		Alamofire.request(.GET, URL_REQUEST_SMS_TOKEN, parameters: apiParams.build())
			.responseJSON { response in
				switch response.result {
				case .Success(let value as NSDictionary):
					if (value["status"] as! Int == 200) {
//                        print(value["data"]!["access_token"])
//                        print(value["data"]!["refresh_token"])
						NSUserDefaults.setAccessToken(value["data"]!["access_token"] as? String)
						NSUserDefaults.standardUserDefaults().setObject(value["data"]!["refresh_token"], forKey: "refresh_token")
						NSUserDefaults.standardUserDefaults().setObject(phoneNumber, forKey: "phone_number")
						self.actionAfterLogin()
						callback(true, "成功！")
						NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.LOGIN_NOTIFICATION, object: nil)
					} else {
						callback(false, value["message"] as? String)
					}
				case .Failure(_):
					callback(false, "连接服务器失败...")
				default:
					callback(false, "未知错误！")
				}
		}
	}

	func logout() {
		guard NSUserDefaults.getAccessToken() != nil else {
			print("\(#function) --> User has not logined")
			return
		}
		NSUserDefaults.setAccessToken(nil)
		try! uiRealm.write {
			uiRealm.deleteAll()
		}
		let cal = Calendar()
		cal.summary = "主日历本"
		cal.category = CATEGORY_SYSTEM
		cal.source = SOURCE_MAIN
		cal.calendarId = "10086"
		cal.localId = 0
		let cal_dd = Calendar()
		cal_dd.summary = "Deadline"
		cal_dd.category = CATEGORY_SYSTEM
		cal_dd.source = SOURCE_DEADLINE
		cal_dd.calendarId = "10088"
		cal_dd.localId = 1
		try! uiRealm.write {
			uiRealm.add(cal)
			uiRealm.add(cal_dd)
		}
        
        NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
		NSUserDefaults.setCurrentCalendarId("10086")
		NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.LOGOUT_NOTIFICATION, object: nil)
	}

	func uploadMainCalendar() {
		let sys_cal = uiRealm.objects(Calendar).filter("category = %@ AND source = %@", CATEGORY_SYSTEM, SOURCE_MAIN).first
		let api = ApiSync()
		// 上传主日历本
		api.updateCalendarToServiceSync(sys_cal!, isAdd: true) {
			response, error in
			// if (response!["result"] as! Bool == false &&
			// response!["status"] as! String == "-10086") {
			// // 重复建立日历本
			// }
            let old_cal_id = sys_cal!.calendarId
			let cal_id = response!["data"]!["calendar_id"] as! String
            
			let systemEvents = uiRealm.objects(Event).filter("calendarId = \"10086\"")
            
			try! uiRealm.write {
				sys_cal!.calendarId = cal_id
				sys_cal!.etag = response!["data"]!["calendarEntry"]!!["etag"] as! String
			}
            
            //更改当前主函数的cal_id后抛出Notification，并且抛出更改当前日历的选项
            //注意两个的顺序不能更改，否则会出错
            let userInfo = [YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_OLD_CAL_ID: old_cal_id, YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_NEW_CAL_ID: cal_id]
            NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_CALENDAR_CAL_ID, object: nil, userInfo: userInfo)
            
            NSUserDefaults.setCurrentCalendarId(cal_id)
            
            print("Main calendar upload complete")
            
			for i in systemEvents {
				api.updateEventToService(i, isAdd: true, calendarId: cal_id, callback: { (response, error) in
					// 上传默认日历本中的事件
					try! uiRealm.write {
						i.etag = response!["data"]!["etag"] as! String
						i.calendarId = cal_id

					}
				})
			}
			NSLog("Upload complete")
			// try! uiRealm.write {
			// uiRealm.delete(sys_cal!)
			// }
		}
	}

	func uploadDeadlineCalendar() {
		let dd_cal = uiRealm.objects(Calendar).filter("category = %@ AND source = %@", CATEGORY_SYSTEM, SOURCE_DEADLINE).first
		let api = ApiSync()
		// 上传deadline
		api.updateCalendarToServiceSync(dd_cal!, isAdd: true) {
			response, error in
            
            let old_cal_id = dd_cal!.calendarId
			let cal_id = response!["data"]!["calendar_id"] as! String
            
			let systemEvents = uiRealm.objects(Event).filter("calendarId = \"10088\"")
            
			try! uiRealm.write {
				dd_cal!.calendarId = cal_id
				dd_cal!.etag = response!["data"]!["calendarEntry"]!!["etag"] as! String
			}
            
            //抛出更改UserInfo的Notification
            let userInfo = [
                YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_OLD_CAL_ID: old_cal_id,
                YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_NEW_CAL_ID: cal_id
            ]
            NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_CALENDAR_CAL_ID, object: nil, userInfo: userInfo)
            
            print("Deadline calendar upload complete")
            
			for i in systemEvents {
				api.updateEventToService(i, isAdd: true, calendarId: cal_id, callback: { (response, error) in
					try! uiRealm.write {
						i.etag = response!["data"]!["etag"] as! String
						i.calendarId = cal_id
					}
				})
			}
			// try! uiRealm.write {
			// uiRealm.delete(dd_cal!)
			// }
		}
	}

	func actionAfterLogin() {
		let otherCalendars = uiRealm.objects(Calendar).filter("category != %@ AND isLocal = true", CATEGORY_SYSTEM)
		let api = ApiSync()
		api.pullCalendarList() {
			response, error in
			// print(response)
			for i in response!["data"]["data"].array! {
				let result = i["calendar"].dictionary
				let cal = Calendar()
				if !(result!["deleted"]!.boolValue) {
					cal.calendarId = i["calendar_id"].stringValue
					if result != nil {
						cal.uuid = result!["uuid"]!.stringValue
						cal.version = result!["version"]!.intValue
						cal.source = result!["source"]!.stringValue
						cal.category = result!["category"]!.stringValue
						cal.summary = result!["summary"]!.stringValue
						// cal.createTime = NSDate(timeIntervalSince1970: result["summary"]!.doubleValue / 1000)
					}
					if (cal.category != CATEGORY_SYSTEM) {
						try! uiRealm.write {
							uiRealm.add(cal)
						}
					}
					for j in i["event"].array! {
						let event = Event()
						if !j["deleted"].boolValue {
                            event.uuid = j["uuid"].stringValue
							event.calendarId = cal.calendarId
							event.version = j["version"].intValue
							event.etag = j["etag"].stringValue
							event.type = j["type"].intValue
							event.summary = j["summary"].stringValue
							event.descriptions = j["description"].stringValue
							event.location = j["location"].stringValue
							event.timezone = j["timezone"].stringValue
							event.color = j["color"].stringValue
                            event.reminders = j["reminders"].stringValue
							event.wholeDayEvent = j["wholeDayEvent"].boolValue
							event.timeBegin = NSDate(timeIntervalSince1970: Double(j["timeBegin"].stringValue)! / 1000)
							event.timeEnd = NSDate(timeIntervalSince1970: Double(j["timeEnd"].stringValue)! / 1000)
                            event.deleted = j["deleted"].boolValue
//                            print(event)
							try! uiRealm.write {
								uiRealm.add(event)
							}
						}
					}
                }
            }
            NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_ALL_CALENDARS, object: nil)
            
			self.uploadMainCalendar()
			self.uploadDeadlineCalendar()
            
            // 上传其它日历本
			for i in otherCalendars {
				api.updateCalendarToServiceSync(i, isAdd: true, callback: { (response, error) in
                    let old_cal_id = i.calendarId
					let cal_id = response!["data"]!["calendar_id"] as! String
					let otherEvents = uiRealm.objects(Event).filter("calendarId == %@", i.calendarId)
					try! uiRealm.write {
						i.calendarId = cal_id
						i.etag = response!["data"]!["calendarEntry"]!!["etag"] as! String
					}
                    
                    //抛出更改Calendar的User Info的通知
                    let userInfo = [
                        YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_OLD_CAL_ID: old_cal_id,
                        YOKONotification.UPDATE_CALENDAR_USERINFO_PARAM_NEW_CAL_ID: cal_id
                    ]
                    NSNotificationCenter.defaultCenter().postNotificationName(YOKONotification.UPDATE_CALENDAR_CAL_ID, object: nil, userInfo: userInfo)
                    
					for j in otherEvents {
						api.updateEventToService(j, isAdd: true, calendarId: cal_id, callback: { (response, error) in
							try! uiRealm.write {
								j.etag = response!["data"]!["etag"] as! String
								j.calendarId = cal_id
							}
						})
					}
				})
			}
		}
	}

}